package org.example;

import java.util.Arrays;
import java.util.Comparator;
import java.util.PriorityQueue;

public class PriorityQueueSortTop {
    public static void main(String[] args) {
        PriorityQueue<Integer> queue = new PriorityQueue<>(new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o2-o1;
            }
        });
        int[] arr = {1,3,5,7,2,4,6,8};
        int k = 4;
        for (int i = 0; i < k; i++) {
            queue.add(arr[i]);
        }
        for (int i = k; i < arr.length; i++) {
            if(arr[i] < queue.peek()){
                queue.poll();
                queue.offer(arr[i]);
            }
        }
        int index = 0;
        int[] newArr = new int[k];
        //现在堆中的前k个元素就是我们要求的前k个最小的元素
        while (!queue.isEmpty()){
            newArr[index] = queue.peek();
            queue.poll();
            index++;
        }
        System.out.println(Arrays.toString(newArr));

    }
}
